/**
 * Created by leo on 16-12-6.
 */

'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Story = mongoose.model('Story'),
  Photo = mongoose.model('Photo'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create an Story
 */
exports.create = function (req, res) {
  var story = new Story(req.body);
  story.creator = req.user;

  story.save(function (err) {
    if (err) {
      res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(story);
    }
  });
};

/**
 * Show the current story
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var story = req.story ? req.story.toJSON() : {};

  // Add a custom field to the Story, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Story model.
  story.isCurrentUserOwner = checkIsInStory(story, req.user);

  res.json(story);
};

/**
 * Update an story
 */
exports.update = function (req, res) {
  var story = req.story;

  if (req.body.title) story.title = req.body.title;
  if (req.body.description) story.description = req.body.description;
  if (req.body.end_date) story.end_date = req.body.end_date;

  story.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(story);
    }
  });
};

/**
 * Delete an story
 */
exports.delete = function (req, res) {
  var story = req.story;

  if (story.creator._id.toString() === req.user._id.toString()) {
    // delete all photos ref to that story
    Photo.find({ in_story: story._id }).exec(function (err, photos) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        for (var i = 0; i < photos.length; ++i) {
          photos[i].remove(function (err) {
            if (err) return res.status(422).send();
          });
        }
      }
    });

    // delete story from database
    story.remove(function (err) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(story);
      }
    });
  } else {
    return res.status(403).send({
      message: 'you are not the create of the story'
    });
  }
};

/**
 * List of stories
 */
exports.list = function (req, res) {
  Story.find({ $or: [{ creator: req.user._id }, { members: req.user._id }] })
    .sort('-start_date').populate('creator').populate('members').populate('photos').exec(function (err, stories) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(stories);
      }
    });
};

/**
 * Story middleware
 */
exports.storyByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Story id is invalid'
    });
  }

  Story.findById(id).populate('creator').populate('members').populate('photos').exec(function (err, story) {
    if (err) {
      return next(err);
    } else if (!story) {
      return res.status(404).send({
        message: 'No story with that identifier has been found'
      });
    }
    req.story = story;
    next();
  });
};

function checkIsInStory(story, user) {
  if (story && user) {
    if (story.creator._id.toString() === user._id.toString()) return true;
    for (var i = 0; i < story.members.length; ++i) {
      if (story.members[i]._id.toString() === user._id.toString()) return true;
    }
  }
  return false;
}
